
package hcb.dms;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * This shows how to create a simple activity with a map and a marker on the map.
 * <p>
 * Notice how we deal with the possibility that the Google Play services APK is not
 * installed/enabled/updated on a user's device.
 */
public class MultiPointMapActivity extends android.support.v4.app.FragmentActivity {
    /**
     * Note that this may be null if the Google Play services APK is not available.
     */
    private GoogleMap mMap;
    private String pid = "";
    private String maKH = "";
    private String tenKH ="";
    private String diaChi = "";
    private String gpsLat = "";
    private String gpsLong = "";


    private static final String TAG_MESSAGE = "message";


    private static final String TAG_GHICHU = "ghiChu";
    private static final String TAG_MST = "maSoThue";
    public static GPSTracker gps;

    private static final String TAG_SUCCESS = "success";
    private static final String TAG_KHACHHANG = "khachHang";
    private static final String TAG_MAKH = "maKH";
    private static final String TAG_TENKH = "tenKH";
    private static final String TAG_DIACHI = "diaChi";
    private static final String TAG_LIENHE = "lienHe";
    private static final String TAG_DIENTHOAI = "dienThoai";
    private static final String TAG_GPSLAT = "gpsLat";
    private static final String TAG_GPSLONG = "gpsLong";
    private static final String TAG_NAME = "name";

    // products JSONArray
    JSONArray products = null;
    UserSessionManager session;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.basic_demo);

        Intent i = getIntent();
        session = new UserSessionManager(getApplicationContext());
        // getting product id (pid) from intent
        String str  = i.getStringExtra(TAG_KHACHHANG);
        String ten = getIntent().getStringExtra(TAG_NAME);

        try {
            JSONArray jsonObj = new JSONArray(str);
            products = jsonObj;
        } catch (JSONException e) {
            Toast.makeText(this, "Thong tin json chuyen sang "+ str.toString(), Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
        try {
            setUpMapIfNeeded();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
            setUpMapIfNeeded();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
     * installed) and the map has not already been instantiated.. This will ensure that we only ever
     * call {@link #setUpMap()} once when {@link #mMap} is not null.
     * <p>
     * If it isn't installed {@link SupportMapFragment} (and
     * {@link com.google.android.gms.maps.MapView
     * MapView}) will show a prompt for the user to install/update the Google Play services APK on
     * their device.
     * <p>
     * A user can return to this Activity after following the prompt and correctly
     * installing/updating/enabling the Google Play services. Since the Activity may not have been
     * completely destroyed during this process (it is likely that it would only be stopped or
     * paused), {@link #onCreate(Bundle)} may not be called again so we should call this method in
     * {@link #onResume()} to guarantee that it will be called.
     */
    private void setUpMapIfNeeded() throws JSONException {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();
            }
        }
    }

    /**
     * This is where we can add markers or lines, add listeners or move the camera. In this case, we
     * just add a marker near Africa.
     * <p>
     * This should only be called once and when we are sure that {@link #mMap} is not null.
     */

    private void setUpMap() throws JSONException {
        gps = new GPSTracker(MultiPointMapActivity.this);

        double latitude =  10.775255;
        double longitude =  106.661819;

        if (gps.canGetLocation()) {

            latitude = gps.getLatitude();
            longitude = gps.getLongitude();
        }

        CameraUpdate center= CameraUpdateFactory.newLatLng(new LatLng(latitude, longitude));
        CameraUpdate zoom=CameraUpdateFactory.zoomTo(15);

        mMap.moveCamera(center);
        mMap.animateCamera(zoom);
        mMap.setMyLocationEnabled(true);
        //  mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
        Toast.makeText(this, "So dong thong tin json trong products: "+ products.length(), Toast.LENGTH_SHORT).show();
        for (int i = 0; i < products.length(); i++) {
            JSONObject c = products.getJSONObject(i);
            // Storing each json item in variable
            String id = c.getString(TAG_MAKH);
            String ten = c.getString(TAG_TENKH);
            String diaChi = c.getString(TAG_DIACHI);

            String gpsLat = c.getString(TAG_GPSLAT);
            String gpsLong = c.getString(TAG_GPSLONG);
            Log.d("Dong " + i, ten);
            mMap.addMarker(new MarkerOptions().position(new LatLng(Double.parseDouble(gpsLat), Double.parseDouble(gpsLong))).title(ten+" "+diaChi));
        }
    }
}
